package cn.cxq.learning.stack;

import java.awt.geom.Arc2D;
import java.util.Stack;

public class SimpleCalculator {

    private Stack<Double> numberStack;
    private Stack<Character> symbolStack;

    public SimpleCalculator() {
        this.numberStack = new Stack<>();
        this.symbolStack = new Stack<>();
    }

    public double calculate(String expression){

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c > '0' && c < '9' || c == '.'){
                //可能不止一位数字
                buffer.append(c);
            }else {
                //数字压栈
                this.numberStack.push(Double.parseDouble(buffer.toString()));
                //清空StringBuffer
                buffer = new StringBuffer();
                if (symbolStack.empty()||((symbolStack.peek()=='+'||symbolStack.peek()=='-')&&(c == '*'||c == '/'))) symbolStack.push(c);
                else {
                    char ch = symbolStack.pop();
                    double b = numberStack.pop();
                    double a = numberStack.pop();
                    switch (ch){
                        case '+':
                            numberStack.push(a + b);
                            break;
                        case '-':
                            numberStack.push(a - b);
                            break;
                        case '*':
                            numberStack.push(a * b);
                            break;
                        case '/':
                            numberStack.push(a / b);
                            break;
                        default:
                            throw new RuntimeException("符号未知~~~");
                    }
                    symbolStack.push(c);
                }
            }
        }

        numberStack.push(Double.parseDouble(buffer.toString()));

        //最后会剩一组数字和符号
        double result;
        char ch = symbolStack.pop();
        double b = numberStack.pop();
        double a = numberStack.pop();
        switch (ch){
            case '+':
                result = a + b;
                break;
            case '-':
                result = a - b;
                break;
            case '*':
                result = a * b;
                break;
            case '/':
                result = a / b;
                break;
            default:
                throw new RuntimeException("符号未知~~~");
        }
        return result;
    }
}
